package service

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc/service"
	"gitee.com/sansaniot/ssiot-core/utils"
	"os"
	"ssadmin/common/constant"
	dto "ssadmin/common/query"
	"ssadmin/internal/admin/models"
	"ssadmin/internal/admin/models/command"
	"ssadmin/internal/admin/models/query"
	"strings"
)

type File struct {
	resourceModel *models.Resource
	service.Service
}

func (d *File) SetItemModel(m *models.Resource) *File {
	d.resourceModel = m
	return d
}

// 删除文件
func (d *File) DeleteFileItem(req *command.FileDeleteReq) (err error) {
	delIds := strings.Split(strings.ReplaceAll(req.Id, " ", ""), ",")
	// 获取路径
	list := make([]models.Resource, 0)
	condition := dto.MakeCondition(query.ItemQuery{IdPathIn: delIds})
	if err = d.resourceModel.FindList(&list, condition); err != nil {
		return
	}
	// 删文件
	for _, v := range list {
		// 删原文件
		_ = os.Remove(constant.FilePath + "/" + v.Path)
		// 删缩略图
		suffix := utils.GetExt(v.Path)
		withoutSuffix := strings.ReplaceAll(v.Path, suffix, "")
		thumbnailImagePath := withoutSuffix + constant.ThumbnailConcat + suffix
		_ = os.Remove(constant.FilePath + "/" + thumbnailImagePath)
	}
	// 删信息
	if err = d.resourceModel.Delete(d.resourceModel, condition); err != nil {
		return err
	}
	return
}
